/*
 * log.cpp
 *
 *  Created on: Apr 22, 2009
 *      Author: kuncai
 */
#include "log.h"
Log::Log()
{
}

Log::~Log()
{
	if(fDEBUGfd != NULL)
	{
		fclose(fDEBUGfd);
	}
	if(fINFOfd != NULL)
	{
		fclose(fINFOfd);
	}
}

int Log::DEBUG = 0; 
int Log::INFO = 0; 
int Log::DEBUGTOFILE = 0; 
int Log::INFOTOFILE = 0; 
string Log::sFilenameDebug = "log_debug.txt";
string Log::sFilenameInfo = "log_info.txt";
FILE* Log::fDEBUGfd = NULL;
FILE* Log::fINFOfd = NULL;
void Log::Config(int debug, int info, int debugtofile, int infotofile, string filename)
{
	DEBUG = debug;
	INFO  = info;
	DEBUGTOFILE = debugtofile;
	INFOTOFILE = infotofile;
	sFilenameDebug = filename;
	if(fDEBUGfd != NULL)
	{
		fclose(fDEBUGfd);
		fDEBUGfd = NULL;
	}
	if(fINFOfd != NULL)
	{
		fclose(fINFOfd);
		fINFOfd = NULL;
	}
}
void Log::Debug(const char* format,...)
{
	if(DEBUG)
	{
		time_t timep;
		time(&timep);
		char* strtime_n = ctime(&timep);
		char strtime[30]="";
		memcpy(strtime,strtime_n,strlen(strtime_n)-1);
		va_list ap;
		va_start(ap,format);
		if(DEBUGTOFILE)
		{
			if(fDEBUGfd == NULL)	
			{
				const char* cFilename = sFilenameDebug.c_str();
				fDEBUGfd = fopen(cFilename,"a+");
				if(fDEBUGfd == NULL)
				{
					perror("fopen debugfd\n");
					return;
				}
			}
			fprintf(fDEBUGfd,"%s : ",strtime);
			vfprintf(fDEBUGfd,format,ap);
		}
		else
		{
			printf("%s : ",strtime);
			vprintf(format,ap);
		}
		va_end(ap);
	}
}

void Log::Info(const char* format,...)
{
	if(INFO)
	{
		va_list ap;
		va_start(ap,format);
		if(INFOTOFILE)
		{
			if(fINFOfd == NULL)	
			{
				const char* cFilename = sFilenameInfo.c_str();
				fINFOfd = fopen(cFilename,"a+");
				if(fINFOfd == NULL)
				{
					perror("fopen infofd\n");
					return;
				}
			}
			vfprintf(fINFOfd,format,ap);
		}
		else
		{
			vprintf(format,ap);
		}
		va_end(ap);
	}

}
